/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.persistence.entity;

import com.je.bpm.engine.delegate.event.ActivitiEventDispatcher;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.ActivitiVariableEvent;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.persistence.CountingExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.data.DataManager;
import com.je.bpm.engine.impl.persistence.entity.data.VariableInstanceDataManager;
import com.je.bpm.engine.impl.variable.VariableType;

import java.util.*;

/**
 *
 */
public class VariableInstanceEntityManagerImpl extends AbstractEntityManager<VariableInstanceEntity> implements VariableInstanceEntityManager {

    protected VariableInstanceDataManager variableInstanceDataManager;

    private static final String[] DELETE_VAR_NAME = {"upcomingInfo", "isJump", "comment"};

    public VariableInstanceEntityManagerImpl(ProcessEngineConfigurationImpl processEngineConfiguration, VariableInstanceDataManager variableInstanceDataManager) {
        super(processEngineConfiguration);
        this.variableInstanceDataManager = variableInstanceDataManager;
    }

    @Override
    protected DataManager<VariableInstanceEntity> getDataManager() {
        return variableInstanceDataManager;
    }

    @Override
    public VariableInstanceEntity create(String name, VariableType type, Object value) {
        VariableInstanceEntity variableInstance = create();
        variableInstance.setName(name);
        variableInstance.setType(type);
        variableInstance.setTypeName(type.getTypeName());
        variableInstance.setValue(value);
        return variableInstance;
    }

    @Override
    public void insert(VariableInstanceEntity entity, boolean fireCreateEvent) {
        super.insert(entity, fireCreateEvent);

        if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) {
            CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById(entity.getExecutionId());
            if (isExecutionRelatedEntityCountEnabled(executionEntity)) {
                executionEntity.setVariableCount(executionEntity.getVariableCount() + 1);
            }
        }
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByTaskId(String taskId) {
        return variableInstanceDataManager.findVariableInstancesByTaskId(taskId);
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByTaskIds(Set<String> taskIds) {
        return variableInstanceDataManager.findVariableInstancesByTaskIds(taskIds);
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByExecutionId(final String executionId) {
        return variableInstanceDataManager.findVariableInstancesByExecutionId(executionId);
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByExecutionIds(Set<String> executionIds) {
        return variableInstanceDataManager.findVariableInstancesByExecutionIds(executionIds);
    }

    @Override
    public VariableInstanceEntity findVariableInstanceByExecutionAndName(String executionId, String variableName) {
        return variableInstanceDataManager.findVariableInstanceByExecutionAndName(executionId, variableName);
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByExecutionAndNames(String executionId, Collection<String> names) {
        return variableInstanceDataManager.findVariableInstancesByExecutionAndNames(executionId, names);
    }

    @Override
    public VariableInstanceEntity findVariableInstanceByTaskAndName(String taskId, String variableName) {
        return variableInstanceDataManager.findVariableInstanceByTaskAndName(taskId, variableName);
    }

    @Override
    public List<VariableInstanceEntity> findVariableInstancesByTaskAndNames(String taskId, Collection<String> names) {
        return variableInstanceDataManager.findVariableInstancesByTaskAndNames(taskId, names);
    }

    @Override
    public void delete(VariableInstanceEntity entity, boolean fireDeleteEvent) {
        super.delete(entity, false);
        ByteArrayRef byteArrayRef = entity.getByteArrayRef();
        if (byteArrayRef != null) {
            byteArrayRef.delete();
        }
        entity.setDeleted(true);

        if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) {
            CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById(entity.getExecutionId());
            if (isExecutionRelatedEntityCountEnabled(executionEntity)) {
                executionEntity.setVariableCount(executionEntity.getVariableCount() - 1);
            }
        }

        ActivitiEventDispatcher eventDispatcher = getEventDispatcher();
        if (fireDeleteEvent && eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, entity));

            eventDispatcher.dispatchEvent(createVariableDeleteEvent(entity));
        }

    }

    protected ActivitiVariableEvent createVariableDeleteEvent(VariableInstanceEntity variableInstance) {

        String processDefinitionId = null;
        if (variableInstance.getProcessInstanceId() != null) {
            ExecutionEntity executionEntity = getExecutionEntityManager().findById(variableInstance.getProcessInstanceId());
            if (executionEntity != null) {
                processDefinitionId = executionEntity.getProcessDefinitionId();
            }
        }

        Object variableValue = null;
        boolean getValue = true;

        if (variableInstance.getType().getTypeName().equals("jpa-entity")) {
            getValue = false;
        }

        if (getValue) variableValue = variableInstance.getValue();

        return ActivitiEventBuilder.createVariableEvent(ActivitiEventType.VARIABLE_DELETED,
                variableInstance.getName(),
                variableValue,
                variableInstance.getType(),
                variableInstance.getTaskId(),
                variableInstance.getExecutionId(),
                variableInstance.getProcessInstanceId(),
                processDefinitionId);
    }

    @Override
    public void deleteVariableInstanceByTask(TaskEntity task) {
        Map<String, VariableInstanceEntity> variableInstances = task.getVariableInstanceEntities();
        if (variableInstances != null) {
            for (VariableInstanceEntity variableInstance : variableInstances.values()) {
                delete(variableInstance);
            }
        }
    }

    public VariableInstanceDataManager getVariableInstanceDataManager() {
        return variableInstanceDataManager;
    }

    public void setVariableInstanceDataManager(VariableInstanceDataManager variableInstanceDataManager) {
        this.variableInstanceDataManager = variableInstanceDataManager;
    }


    @Override
    public void deleteGarbageVariableInstanceByProcessInstanceId(String piid) {
        List<VariableInstanceEntity> variableInstances = variableInstanceDataManager.findVariableInstancesByProcessInstanceId(piid);
        if (variableInstances != null) {
            for (VariableInstanceEntity variableInstance : variableInstances) {
                int index = Arrays.binarySearch(DELETE_VAR_NAME, variableInstance.getName());
                if (index >= 0) {
                    delete(variableInstance);
                }
            }
        }
    }
}
